package co.th.bjc.md.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import co.th.bjc.md.dao.Province;

import net.sf.json.JSONArray;

/**
 * Servlet implementation class ProvinceManageServlet
 */
public class ProvinceManageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProvinceManageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html; charset=UTF-8");
		JSONArray jsonObject = new JSONArray();
		boolean status = false;
		String action = request.getParameter("action")==null?"":request.getParameter("action");
		
		if(action.equals("SEARCH")){
			PrintWriter out = response.getWriter();
			jsonObject = this.getSearchResult(request, response);
			out.print(jsonObject);
		}else if(action.equals("DELETE")){
			// Delete process
			if(this.delete(request, response)){
				PrintWriter out = response.getWriter();
				status = true;
				jsonObject = this.getSearchResult(request, response);
				jsonObject.add(status);
				out.print(jsonObject);
			}
		}else if(action.equals("GETEDIT")){
			PrintWriter out = response.getWriter();
			jsonObject = getEditItem(request, response);
			status = true;
			jsonObject.add(status);
			out.print(jsonObject);
		}else{
			getServletContext().getRequestDispatcher("/jsp/datamanage/manage_province_main.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html; charset=UTF-8");
		Hashtable multipartParams;
		try {
			multipartParams = ProvinceManageServlet.getParamsFromMultipartForm(request);
			Province obj = new Province();
			obj.setProvinceId(BigDecimal.valueOf(Long.parseLong((String)multipartParams.get("province_id"))));
			obj.setProvinceNameEn((String)multipartParams.get("ins_province_name_en"));
			obj.setProvinceNameTH((String)multipartParams.get("ins_province_name_th"));
			
			System.out.println("Success");
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Hashtable getParamsFromMultipartForm(HttpServletRequest req) throws FileUploadException {
        Hashtable ret = new Hashtable();
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
        for (FileItem item : items) {
            if (item.isFormField()) {
                ret.put(item.getFieldName(), item.getString());
            }
        }
        return ret;
    }
	
	private JSONArray getSearchResult(HttpServletRequest request, HttpServletResponse response) {
		String srhName = request.getParameter("srh_province_name") == null?"":request.getParameter("srh_province_name");
		List<Province> list = new ArrayList<Province>();
		Province obj = new Province();
		obj.setProvinceId(BigDecimal.valueOf(Long.parseLong("1")));
		obj.setProvinceNameEn("Bangkok");
		obj.setProvinceNameTH("กรุงเทพมหานคร");
		list.add(obj);
		Province obj1 = new Province();
		obj1.setProvinceId(BigDecimal.valueOf(Long.parseLong("2")));
		obj1.setProvinceNameEn("Chiangmai");
		obj1.setProvinceNameTH("เชียงใหม่");
		list.add(obj1);
		JSONArray jsonObject = JSONArray.fromObject(list);
		return jsonObject;
	}
	
	private boolean delete(HttpServletRequest request, HttpServletResponse response){
		BigDecimal id = BigDecimal.valueOf(Long.parseLong(request.getParameter("id")));
		return false;
	}
	
	private JSONArray getEditItem(HttpServletRequest request, HttpServletResponse response){
		BigDecimal id = BigDecimal.valueOf(Long.parseLong(request.getParameter("id")));
		Province obj = new Province();
		obj.setProvinceId(BigDecimal.valueOf(Long.parseLong("1")));
		obj.setProvinceNameEn("Bangkok");
		obj.setProvinceNameTH("กรุงเทพมหานคร");
		JSONArray json = JSONArray.fromObject(obj);
		return json;
	}

}
